package com.huonan.jb.tools.fileuse.fitdata;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huonan.utils.ExecutorUtil;
import com.huonan.utils.FileUtils2;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * @Description es跟新文件格式化
 * @Author lxp
 * @Date 2023/3/31 下午2:08
 * @Version V1.0
 **/
@Slf4j
public class CdEsOperation {

    public static final String PREFIX = "format_";

    public static void main(String[] args) throws IOException {
        ExecutorService executor = ExecutorUtil.getExecutorService(10);
        String path = args[0];
        log.info("输入路径:{}", path);
        String parentPath = FileUtil.getParent(path, 1) + FileUtil.FILE_SEPARATOR + "format";
        if (FileUtil.isDirectory(path)) {
            List<File> files = FileUtil.loopFiles(path);
            for (File file : files) {
                log.info("处理文件:{}", file.getAbsolutePath());
                CompletableFuture.runAsync(() -> {
                    List<String> list = formatFile(file);
                    FileUtil.appendUtf8Lines(list, parentPath + FileUtil.FILE_SEPARATOR + PREFIX + file.getName());
                }, executor);
            }
        } else {
            File file = new File(path);
            log.info("处理文件:{}", file.getAbsolutePath());
            CompletableFuture.runAsync(() -> {
                List<String> list = formatFile(file);
                FileUtil.appendUtf8Lines(list, parentPath + FileUtil.FILE_SEPARATOR + PREFIX + file.getName());
            }, executor);
        }
        ExecutorUtil.closePool(executor);
    }

    private static List<String> formatFile(File file) {
        List<String> newList = new ArrayList<>();
        try (FileUtils2 reader = new FileUtils2(file.getAbsolutePath(), 2000)) {
            while (true) {
                List<String> lines = reader.readNextLines();
                if (lines.size() == 0) {
                    break;
                }
                List<String> collect = lines.stream()
                        .map(l -> {
                            JSONObject entries = JSONUtil.parseObj(l);
                            entries.putOpt("_type", "ec");
                            return JSONUtil.toJsonStr(entries);
                        }).collect(Collectors.toList());
                newList.addAll(collect);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newList;
    }


}
